﻿@page "/Schedule/{Id:guid?}"
@page "/Schedule/{Action}/{Id:guid?}"

@using Gurux.DLMS.AMI.Client.Pages.Device
@using Gurux.DLMS.AMI.Client.Pages.DeviceTemplate
@using Gurux.DLMS.AMI.Client.Pages.Module
@using Gurux.DLMS.AMI.Client.Pages.Objects
@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.Rest;
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs.Authentication
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Shared.DTOs
@using System.Globalization;

@attribute [Authorize(Roles = GXRoles.Admin + "," + GXRoles.ScheduleManager + "," + GXRoles.ScheduleGroupManager)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier

@if (_modulesSelector?.Active != null)
{
    <ScheduleEdit @ref="_scheduleEdit"
                  Module="@_modulesSelector.Active"
                  Schedule="@Active"></ScheduleEdit>
}
else
{
    <CascadingValue Value="this">
        <TabControl InitialTab="@_initialTab">
            <TabTextTemplate>
                <span class=@context.Icon aria-hidden="true"></span>
                @context.Text
            </TabTextTemplate>
            <ChildContent>
                <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.ScheduleManager)>
                    <TabPage Text=@Properties.Resources.GeneralInformation Icon="oi oi-timer">
                        <Schedule Action="@Action"></Schedule>
                    </TabPage>
                </AuthorizeView>
                <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.UserGroupManager, GXRoles.UserGroup)>
                    <TabPage Text=@Properties.Resources.ScheduleGroups Icon="oi oi-timer">
                        <ScheduleGroupsSelector></ScheduleGroupsSelector>
                    </TabPage>
                </AuthorizeView>
                <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.DeviceManager, GXRoles.Device)>
                    <TabPage Text=@Properties.Resources.DevicesTitle Icon="oi oi-timer">
                        <DeviceSelector Devices="@Active.Devices"
                                        ObjectTemplates="@Active.DeviceObjectTemplates"
                                        AttributeTemplates="@Active.DeviceAttributeTemplates">
                        </DeviceSelector>
                    </TabPage>
                </AuthorizeView>
                <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.DeviceGroupManager, GXRoles.DeviceGroup)>
                    <TabPage Text=@Properties.Resources.DeviceGroups Icon="oi oi-timer">
                        <DeviceGroupSelector DeviceGroups="@Active.DeviceGroups"
                                             ObjectTemplates="@Active.DeviceGroupObjectTemplates"
                                             AttributeTemplates="@Active.DeviceGroupAttributeTemplates">
                        </DeviceGroupSelector>
                    </TabPage>
                </AuthorizeView>
                <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.UserGroupManager)>
                    <TabPage Text=@Properties.Resources.ModulesTitle Icon="oi oi-timer">
                        <ModulesSelector @ref="_modulesSelector"></ModulesSelector>
                    </TabPage>
                </AuthorizeView>
            </ChildContent>
        </TabControl>
    </CascadingValue>
}
@code {
    [Parameter]
    public string? Action { get; set; }

    int _initialTab = 0;

    [Parameter]
    public Guid? Id { get; set; }

    ModulesSelector? _modulesSelector;
    ScheduleEdit? _scheduleEdit;
    private string? Title;

    /// <summary>
    /// Active item.
    /// </summary>
    public GXSchedule Active = new GXSchedule(null)
        {
            Start = new GXDateTime(@"*/*/* *:00:00", CultureInfo.InvariantCulture).ToFormatString()
        };

    /// <summary>
    /// Close module edit if user is editing
    /// the schedule module.
    /// </summary>
    /// <returns>True, if user is edit the module settings.</returns>
    internal async Task<bool> AcceptChanges(bool cancel)
    {
        if (_modulesSelector != null &&
            _modulesSelector.Active != null)
        {
            if (!cancel && _scheduleEdit != null)
            {
                await _scheduleEdit.SaveAsync();
            }
            _initialTab = 6;
            _modulesSelector.Active = null;
            StateHasChanged();
            return true;
        }
        return false;
    }

    /// <summary>
    /// ModulesSelector asks schedule to update the UI.
    /// </summary>
    internal void Update()
    {
        StateHasChanged();
    }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            switch (Action)
            {
                case "Add":
                    Title = Properties.Resources.Add;
                    break;
                case "Edit":
                    Title = Properties.Resources.Edit;
                    break;
                case "Remove":
                    Title = Properties.Resources.Remove;
                    break;
                default:
                    ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
                    return;
            }
            Title += " " + Properties.Resources.Schedule;
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (string.Compare(Action, "Add", true) != 0)
            {
                //Get schedule data.
                var tmp = (await Http.GetAsJsonAsync<GetScheduleResponse>(string.Format("api/Schedule?id={0}", Id)));
                if (tmp?.Item != null)
                {
                    Active = tmp.Item;
                    //Convert start time from invariant culture to UI culture.
                    Active.Start = new GXDateTime(Active.Start, CultureInfo.InvariantCulture).ToFormatString();
                    StateHasChanged();
                }
                else
                {
                    NavigationManager.NavigateTo("404");
                }
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }
}

